﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using CloudApiServer.Class;
using CloudApiServer.Services;
using Google.Protobuf.WellKnownTypes;
using log4net;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Asn1.X509;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static log4net.Appender.RollingFileAppender;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 浙江医保
    /// </summary>
    [RoutePrefix("fsi/api")]
    public class FsiApiZheJiangController : ApiController
    {
        private readonly SignInSignOutService _signInSignOuService;
        private readonly FsiPsnInfoService  _fsiPsnInfoService;
        private readonly FsiDrugStoreService _fsiDrugStoreService;
        public FsiApiZheJiangController()
        {
            _signInSignOuService = new SignInSignOutService();
            _fsiPsnInfoService = new FsiPsnInfoService();
            _fsiDrugStoreService = new FsiDrugStoreService();
        }

        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string infno = fsiRequest.infno;
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 9001签到
        /// </summary>
        /// <returns></returns>
        [Route("signInSignOutService/signIn")]
        [HttpPost]
        public async Task<IHttpActionResult> signIn(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(await request.Content.ReadAsStringAsync());
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var signin = await _signInSignOuService.SignInAsync(fsiRequest, this.GetType().Name);
                var response = new FsiHeader<outputsignInOut>
                {
                    output = signin,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(response);
            }
            catch (Exception ex)
            {
                string errNum = LogHelper.GetErrornumber();
                var errorResponse = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{errNum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(errorResponse);
            }
        }
        /// <summary>
        /// 9002签退
        /// </summary>
        /// <returns></returns>
        [Route("signInSignOutService/signOut")]
        [HttpPost]
        public async Task<IHttpActionResult> signOut(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignOut>>(request.Content.ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var siginout = await _signInSignOuService.SignOutAsync(fsiRequest,this.GetType().Name);
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    output = siginout,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 1101 人员信息获取
        /// </summary>
        /// <returns></returns>
        [Route("fsiPsnInfoService/queryPsnInfo")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnInfo(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnInfoRequest>>(request.Content.ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                var queryPsnInfo = await _fsiPsnInfoService.QueryPsnInfo(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputQueryPsnInfo>
                {
                    output = queryPsnInfo,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 2101/2101A 药店预结算接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPreA")]
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPre")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsPreA(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleAccountsPreA = await _fsiDrugStoreService.DrugstoreSettleAccountsPre(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                {
                    output = drugstoreSettleAccountsPreA,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 2102/2102A 药店结算接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsA")]
        [Route("fsiDrugStoreService/drugstoreSettleAccounts")]
        [Route("fsiDrugStoreService/drugstoreSettleAccountsV2")]
        [HttpPost]
        public async Task<IHttpActionResult>  drugstoreSettleAccountsA(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleAccountsA = await _fsiDrugStoreService.DrugstoreSettleAccounts(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                {
                    output = drugstoreSettleAccountsA,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 2103退款接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleRevoke")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleRevoke(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleRevokeRequest>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleRevoke = await _fsiDrugStoreService.DrugstoreSettleRevoke(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleRevoke>
                {
                    output = drugstoreSettleRevoke,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 7202接口
        /// </summary>
        /// <returns></returns>
        [Route("opsp/7202")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7202(HttpRequestMessage request)
        {
            //throw new Exception("当前入参：" + request.Content.ReadAsStringAsync().Result);
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputOpsp7202Request>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string psn_name = fsiRequest.Input.data.psn_name;
                    if (string.IsNullOrEmpty(psn_no))
                    {
                        throw new Exception("参数校验失败：传入的人员编号为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count != 0)
                            {
                                List<DataOpsp7202> dataList = new List<DataOpsp7202>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    DataOpsp7202 item = new DataOpsp7202
                                    {
                                        auth_rxno = row["auth_rxno"].ToString(),
                                        epc_token = row["epc_token"].ToString(),
                                        expires_in = row["expires_in"].ToString(),
                                        fixmedins_code = row["fixmedins_code"].ToString(),
                                        fixmedins_name = row["fixmedins_name"].ToString(),
                                        prsc_time = row["prsc_time"].ToString(),
                                        dise_codg = row["dise_codg"].ToString(),
                                        dise_name = row["dise_name"].ToString(),
                                        valid_end_time = row["valid_end_time"].ToString()
                                    };
                                    dataList.Add(item);
                                }
                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                FsiHeader<outputDataOpsp7202> FsiHeader = new FsiHeader<outputDataOpsp7202>
                                {
                                    output = new outputDataOpsp7202
                                    {
                                        data = dataList
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询处方列表失败！人员姓名：{psn_name} 人员编号：{psn_no} 未查询到7202处方列表，如需测试请联系管理员增加相关数据！");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 7203接口
        /// </summary>
        /// <returns></returns>
        [Route("opsp/7203")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7203(HttpRequestMessage request)
        {
            DataTable dtinfo = new DataTable();
            DataTable dtdetail = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputOpsp7203Request>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string epc_token = fsiRequest.Input.data.epc_token ?? fsiRequest.Input.data.epctoken;
                    string auth_rxno = fsiRequest.Input.data.auth_rxno;


                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(epc_token) || string.IsNullOrEmpty(auth_rxno))
                    {
                        throw new Exception("参数校验失败：传入的人员编号|电子处方令牌|医保处方授权编号为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where psn_no=@psn_no and epc_token=@epc_token and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@epc_token", epc_token);
                        cmd.Parameters.AddWithValue("@auth_rxno", auth_rxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtinfo.Load(reader);
                            if (dtinfo.Rows.Count == 0)
                            {
                                throw new Exception($"查询处方列表失败！人员编号：{psn_no}处方授权编号：{auth_rxno} 未查询到处方列表，如需测试请联系管理员增加相关数据！");
                            }
                            cmd.Parameters.Clear();
                        }
                        cmd.CommandText = "select * from fsi_prescription_detail where psn_no=@psn_no and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@epc_token", epc_token);
                        cmd.Parameters.AddWithValue("@auth_rxno", auth_rxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            List<RxDetlList> dataList = new List<RxDetlList>();
                            dtdetail.Load(reader);
                            if (dtdetail.Rows.Count != 0)
                            {
                                foreach (DataRow row in dtdetail.Rows)
                                {
                                    RxDetlList item = new RxDetlList
                                    {
                                        med_list_codg = row["med_list_codg"].ToString(),
                                        fixmedins_hilist_id = row["fixmedins_hilist_id"].ToString(),
                                        hosp_prep_flag = row["hosp_prep_flag"].ToString(),
                                        rx_item_type_code = row["rx_item_type_code"].ToString(),
                                        rx_item_type_name = row["rx_item_type_name"].ToString(),
                                        tcmdrug_type_code = row["tcmdrug_type_code"].ToString(),
                                        tcmdrug_type_name = row["tcmdrug_type_name"].ToString(),
                                        tcmherb_foote = row["tcmherb_foote"].ToString(),
                                        medn_type_code = row["medn_type_code"].ToString(),
                                        medn_type_name = row["medn_type_name"].ToString(),
                                        main_medc_flag = row["main_medc_flag"].ToString(),
                                        urgt_flag = row["urgt_flag"].ToString(),
                                        bas_medn_flag = row["bas_medn_flag"].ToString(),
                                        imp_drug_flag = row["imp_drug_flag"].ToString(),
                                        drug_prodname = row["drug_prodname"].ToString(),
                                        drug_genname = row["drug_genname"].ToString(),
                                        drug_dosform = row["drug_dosform"].ToString(),
                                        drug_spec = row["drug_spec"].ToString(),
                                        prdr_name = row["prdr_name"].ToString(),
                                        drug_cnt = Convert.ToDecimal( row["drug_cnt"]),
                                        medc_way_codg = row["medc_way_codg"].ToString(),
                                        medc_way_dscr = row["medc_way_dscr"].ToString(),
                                        medc_endtime = row["medc_endtime"].ToString(),
                                        medc_begntime = row["medc_begntime"].ToString(),
                                        medc_days = Convert.ToDecimal(row["medc_days"]),
                                        drug_dosunt = row["drug_dosunt"].ToString(),
                                        sin_doscnt = Convert.ToDecimal(row["sin_doscnt"]),
                                        sin_dosunt = row["sin_dosunt"].ToString(),
                                        used_frqu_codg = row["used_frqu_codg"].ToString(),
                                        used_frqu_name = row["used_frqu_name"].ToString(),
                                        drug_totlcnt = row["drug_totlcnt"].ToString(),
                                        drug_totlnt_emp = row["drug_totlnt_emp"].ToString(),
                                        own_expense_flag = row["own_expense_flag"].ToString(),
                                        hi_nego_drug_flag = row["hi_nego_drug_flag"].ToString(),
                                        refer_d_channel_flag = row["refer_d_channel_flag"].ToString(),
                                        bidding_drug_flag = row["bidding_drug_flag"].ToString(),
                                        hosp_appr_flag = row["hosp_appr_flag"].ToString()
                                    };
                                    dataList.Add(item);
                                }
                            }
                            else
                            {
                                throw new Exception($"查询处方明细列表失败！人员编号：{psn_no} 未查询到7203处方药品列表，如需测试请联系管理员增加相关数据！");
                            }
                            cmd.Parameters.Clear();
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                            var FsiHeader = new FsiHeader<outputDataOpsp7203>
                            {
                                output = new outputDataOpsp7203
                                {
                                    data = new DataOpsp7203
                                    {
                                        hi_rxno = dtinfo.Rows[0]["hi_rxno"].ToString(),
                                        fixmedins_code = dtinfo.Rows[0]["fixmedins_code"].ToString(),
                                        fixmedins_name = dtinfo.Rows[0]["fixmedins_name"].ToString(),
                                        prsc_time = dtinfo.Rows[0]["prsc_time"].ToString(),
                                        rx_file = dtinfo.Rows[0]["rx_file"].ToString(),
                                        rx_trace_code = dtinfo.Rows[0]["rx_trace_code"].ToString(),
                                        prsc_dept_name = dtinfo.Rows[0]["prsc_dept_name"].ToString(),
                                        rx_type_code = dtinfo.Rows[0]["rx_type_code"].ToString(),
                                        rx_type_name = dtinfo.Rows[0]["rx_type_name"].ToString(),
                                        long_rx_flag = dtinfo.Rows[0]["long_rx_flag"].ToString(),
                                        file_suffix = dtinfo.Rows[0]["file_suffix"].ToString()

                                    },
                                    rxDetlList= dataList,
                                    rxOtpinfo = new RxOtpinfo
                                    {
                                        med_type = dtinfo.Rows[0]["med_type"].ToString(),
                                        patn_name = dtinfo.Rows[0]["patn_name"].ToString(),
                                        //patn_age = Convert.ToDecimal(dtinfo.Rows[0]["patn_age"]),
                                        patn_hgt = dtinfo.Rows[0]["patn_hgt"].ToString(),
                                        //patn_wt = Convert.ToDecimal(dtinfo.Rows[0]["patn_wt"]),
                                        gend = dtinfo.Rows[0]["gend"].ToString(),
                                        //geso_val = Convert.ToDecimal(dtinfo.Rows[0]["geso_val"]),
                                        nwb_flag = dtinfo.Rows[0]["nwb_flag"].ToString(),
                                        nwb_age = dtinfo.Rows[0]["nwb_age"].ToString(),
                                        //suck_prd_flag = (int)dtinfo.Rows[0]["suck_prd_flag"],
                                        algs_his = dtinfo.Rows[0]["algs_his"].ToString(),
                                        dise_codg = dtinfo.Rows[0]["dise_codg"].ToString(),
                                        dise_name = dtinfo.Rows[0]["dise_name"].ToString(),
                                        otp_ipt_flag = dtinfo.Rows[0]["otp_ipt_flag"].ToString(),
                                        main_diag_code = dtinfo.Rows[0]["main_diag_code"].ToString(),
                                        main_diag_name = dtinfo.Rows[0]["main_diag_name"].ToString(),
                                        dise_cond_dscr = dtinfo.Rows[0]["dise_cond_dscr"].ToString()
                                    }
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 7204处方审核
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7204")]
        [HttpPost]
        public IHttpActionResult opsp7204()
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                Guid uuid = Guid.NewGuid();
                var FsiHeader = new FsiHeader<OutputOpsp7204>
                {
                    output = new OutputOpsp7204
                    {
                        data = new DataOutputOpsp7204
                        {
                            flag = "true",
                            rx_chk_biz_sn = uuid.ToString(),
                            rx_info_verify_result =null
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"  
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 7211处方销售出库
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7211")]
        [HttpPost]
        public IHttpActionResult opsp7211()
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                var FsiHeader = new FsiHeader<OutputOpsp7204>
                {
                    output = new OutputOpsp7204
                    {
                        data = new DataOutputOpsp7204
                        {
                            flag = "true"
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 7000处方药品明细查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7000")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7000(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InuptOpsp7000>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;
                    int page_num = fsiRequest.Input.data.page_num;
                    int page_size = fsiRequest.Input.data.page_size;
                    if (string.IsNullOrEmpty(med_list_codg))
                    {
                        throw new Exception("参数校验失败：传入的医保国家编码为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    int nowpage = page_size * (page_num - 1);
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        //西药中成药
                        if (med_list_codg.StartsWith("X") )
                        {
                            cmd.CommandText = "select med_list_codg,NAT_DRUG_NO,'' as genname, DRUG_PRODNAME as  prodname, reg_name,'101' as list_type, '西药中成药' as list_type_name,DRUG_SPEC as spec_name, PRODENTP_NAME as  prdr_name ,  aprvno, DRUG_DOSFORM as dosform_name,min_pacunt,min_pac_cnt,min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_xyzcyml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        else if( med_list_codg.StartsWith("Z"))
                        {
                            cmd.CommandText = "select med_list_codg,NAT_DRUG_NO,'' as genname, DRUG_PRODNAME as  prodname, reg_name,'101' as list_type, '西药中成药' as list_type_name,DRUG_SPEC as spec_name, PRODENTP_NAME as  prdr_name ,  aprvno, DRUG_DOSFORM as dosform_name,min_pacunt,min_pac_cnt,min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_xyzcyml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        //中药饮片
                        else  if (med_list_codg.StartsWith("T"))
                        {
                            cmd.CommandText = "select med_list_codg,'' as NAT_DRUG_NO,'' as genname, '' as  prodname, tcmherb_name as  reg_name,'102' as list_type, '中药饮片' as list_type_name, cnvl_used as spec_name, '' as  prdr_name , '' as  aprvno, ''  as dosform_name, '' as min_pacunt,'' as min_pac_cnt, ''as min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_zyypml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        else
                        {
                            throw new Exception($"校验国家编码属性失败：{med_list_codg}非法或不满足预设的条件!请检查国家编码是否正确或联系管理员!");
                        }
                        cmd.Parameters.AddWithValue("@med_list_codg", med_list_codg);
                        cmd.Parameters.AddWithValue("@page_size", page_size);
                        cmd.Parameters.AddWithValue("@nowpage", nowpage);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count >= 1)
                            {
                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                var FsiHeader = new FsiHeader<OutputOpsp7000>
                                {
                                    output = new OutputOpsp7000
                                    {
                                        data = new DataOutputOpsp7000
                                        {
                                            total = 10,
                                            Size = dt.Rows.Count,
                                        },
                                        list = new List<ListOutputOpsp7000>
                                        {
                                            new ListOutputOpsp7000
                                            {
                                                med_list_codg = dt.Rows[0]["med_list_codg"].ToString(),
                                                nat_drug_no = dt.Rows[0]["nat_drug_no"].ToString(),
                                                genname = dt.Rows[0]["genname"].ToString(),
                                                prodname = dt.Rows[0]["prodname"].ToString(),
                                                reg_name = dt.Rows[0]["reg_name"].ToString(),
                                                list_type = dt.Rows[0]["list_type"].ToString(),
                                                list_type_name = dt.Rows[0]["list_type_name"].ToString(),
                                                spec_name = dt.Rows[0]["spec_name"].ToString(),
                                                prdr_name = dt.Rows[0]["prdr_name"].ToString(),
                                                aprvno = dt.Rows[0]["aprvno"].ToString(),
                                                dosform_name = dt.Rows[0]["dosform_name"].ToString(),
                                                min_pacunt = dt.Rows[0]["min_pacunt"].ToString(),
                                                min_pac_cnt = dt.Rows[0]["min_pac_cnt"].ToString(),
                                                min_prepunt = dt.Rows[0]["min_prepunt"].ToString(),
                                                poolarea_no = dt.Rows[0]["poolarea_no"].ToString(),
                                                poolarea_name = dt.Rows[0]["poolarea_name"].ToString(),
                                                dualchnl_flag = dt.Rows[0]["dualchnl_flag"].ToString(),
                                                begntime = dt.Rows[0]["begntime"].ToString(),
                                                endtime = dt.Rows[0]["endtime"].ToString(),
                                            }
                                        },
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询目录数据表失败！查询到的医保目录数据总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                    //}

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3301上传对照
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogCompService/catalogCompUp")]
        [HttpPost]
        public async Task<IHttpActionResult> catalogCompUp(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputCatalogCompUp>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DataCatalogCompUp> list = new List<DataCatalogCompUp>();
                    list = fsiRequest.Input.data;
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    if (string.IsNullOrEmpty(fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|上传商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    string error = "";
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.Transaction = transaction;
                            foreach (var item in list)
                            {
                                try
                                {
                                    cmd.CommandText = "INSERT INTO fsi_catalogcompup  VALUES (@fixmedins_code, @fixmedins_hilist_id, @fixmedins_hilist_name,@list_type, @med_list_codg, @begndate, @enddate, @aprvno, @dosform, @exct_cont, @item_cont, @prcunt, @spec, @pacspec, @memo, @scdz, @prdr_name,@create_time)";
                                    cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                    cmd.Parameters.AddWithValue("@fixmedins_hilist_id", item.fixmedins_hilist_id);
                                    cmd.Parameters.AddWithValue("@fixmedins_hilist_name", item.fixmedins_hilist_name);
                                    cmd.Parameters.AddWithValue("@list_type", item.list_type);
                                    cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                    cmd.Parameters.AddWithValue("@begndate", item.begndate);
                                    cmd.Parameters.AddWithValue("@enddate", item.enddate);
                                    cmd.Parameters.AddWithValue("@aprvno", item.aprvno);
                                    cmd.Parameters.AddWithValue("@dosform", item.dosform);
                                    cmd.Parameters.AddWithValue("@exct_cont", item.exct_cont);
                                    cmd.Parameters.AddWithValue("@item_cont", item.item_cont);
                                    cmd.Parameters.AddWithValue("@prcunt", item.prcunt);
                                    cmd.Parameters.AddWithValue("@spec", item.spec);
                                    cmd.Parameters.AddWithValue("@memo", item.memo);
                                    cmd.Parameters.AddWithValue("@scdz", item.scdz);
                                    cmd.Parameters.AddWithValue("@prdr_name", item.prdr_name);
                                    cmd.Parameters.AddWithValue("@create_time", createTime);
                                    await cmd.ExecuteNonQueryAsync();
                                    cmd.Parameters.Clear();
                                }
                                catch (Exception ex)
                                {
                                    error = error + $"【{item.fixmedins_hilist_name}/{item.spec}/{item.prcunt}/{item.prdr_name}/{item.aprvno}】上传出错：" + ex.Message + "|";
                                }
                                cmd.Parameters.Clear();
                            }
                            if (error != "")
                            {
                                transaction.Rollback();
                                throw new Exception(error);

                            }
                            else
                            {
                                transaction.Commit();
                                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                                {
                                    output = null,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 3302上传撤销
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogCompService/deleteCatalogCompAudited")]
        [HttpPost]
        public async Task<IHttpActionResult> deleteCatalogCompAudited(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDeleteCatalogCompAudited>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
                    string fixmedins_hilist_id = fsiRequest.Input.data.fixmedins_hilist_id;
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;

                    if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(fixmedins_hilist_id) || string.IsNullOrEmpty(med_list_codg))
                    {
                        throw new Exception("参数校验失败：传入的机构代码|医疗机构内部编码|医保国家编码为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id ";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询商品上传记录表失败：根据传入的机构代码、医疗机构内部编码未找商品已上传记录！当前入参：" + request.Content.ReadAsStringAsync().Result);
                            }
                            else
                            {
                                cmd.Parameters.Clear();
                                cmd.CommandText = "delete from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id=@fixmedins_hilist_id  ";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fixmedins_hilist_id);
                                await cmd.ExecuteNonQueryAsync();
                                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                                {
                                    output = null,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 1317上传信息查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogqueryservice/queryMedListMapByPage")]
        [HttpPost]
        public async Task<IHttpActionResult> queryMedListMapByPage(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryMedListMapByPageRequest>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.Input.data.fixmedins_code;
                    string medins_list_codg = fsiRequest.Input.data.medins_list_codg;//定点医药机构目录编号
                    string medins_list_name = fsiRequest.Input.data.medins_list_name;//定点医药机构目录名称
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;//医疗目录编码
                    int page_num = fsiRequest.Input.data.page_num;//当前页
                    int page_size = fsiRequest.Input.data.page_size;//本页数据
                    if (string.IsNullOrEmpty(fixmedins_code) || page_num==0|| page_size==0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|当前页码|当前页条数为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    if (string.IsNullOrEmpty(medins_list_codg))
                    {
                        medins_list_codg = "%";
                    }
                    if (string.IsNullOrEmpty(medins_list_name))
                    {
                        medins_list_name = "%";
                    }
                    if (string.IsNullOrEmpty(med_list_codg))
                    {
                        med_list_codg = "%";
                    }
                    int now_page = (page_num-1) * page_size;
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_catalogcompup where fixmedins_code=@fixmedins_code and fixmedins_hilist_id like @medins_list_codg and fixmedins_hilist_name like @medins_list_name and med_list_codg like @med_list_codg limit @nowpage,@pagesize";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedins_code);
                        cmd.Parameters.AddWithValue("@medins_list_codg", "%" + medins_list_codg+ "%");
                        cmd.Parameters.AddWithValue("@medins_list_name", "%" + medins_list_name + "%");
                        cmd.Parameters.AddWithValue("@med_list_codg", "%" + med_list_codg + "%");
                        cmd.Parameters.AddWithValue("@nowpage", now_page);
                        cmd.Parameters.AddWithValue("@pagesize", page_size);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            List<DataQueryMedListMapByPage> dataList = new List<DataQueryMedListMapByPage>();
                            dt.Load(reader);
                            cmd.Parameters.Clear();
                            foreach (DataRow row in dt.Rows)
                            {
                                DataQueryMedListMapByPage item = new DataQueryMedListMapByPage
                                {
                                    fixmedins_code = row["fixmedins_code"].ToString(),
                                    medins_list_codg = row["fixmedins_hilist_id"].ToString(),
                                    medins_list_name = row["fixmedins_hilist_name"].ToString(),
                                    insu_admdvs = fsiRequest.mdtrtarea_admvs.ToString(),
                                    list_type = row["list_type"].ToString(),
                                    med_list_codg = row["med_list_codg"].ToString(),
                                    begndate = row["begndate"].ToString(),
                                    enddate = row["enddate"].ToString(),
                                    aprvno = row["aprvno"].ToString(),
                                    dosform = row["dosform"].ToString(),
                                    exct_cont = row["exct_cont"].ToString(),
                                    item_cont = row["item_cont"].ToString(),
                                    prcunt = row["prcunt"].ToString(),
                                    spec = row["spec"].ToString(),
                                    pacspec = row["pacspec"].ToString(),
                                    memo = row["memo"].ToString(),
                                    updt_time = row["create_time"].ToString(),
                                    crte_time = row["create_time"].ToString()
                                };
                                dataList.Add(item);
                            }
                            FsiHeader<OutputQueryMedListMapByPage> FsiHeader = new FsiHeader<OutputQueryMedListMapByPage>
                            {
                                output = new OutputQueryMedListMapByPage
                                {
                                    data = dataList,
                                    size=1,
                                    startRow=1,
                                    endRow=1,
                                    pageSize=page_size,
                                    pageNum = page_num
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 3201对账汇总
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("ybSettlementStmtService/stmtTotal")]
        [HttpPost]
        public IHttpActionResult stmtTotal(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputStmtTotalRequest>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                var FsiHeader = new FsiHeader<OutputStmtTotal>
                {
                    output = new OutputStmtTotal
                    {
                        stmtinfo = new DataStmtTotal
                        {
                            setl_optins = fsiRequest.insuplc_admdvs,
                            stmt_rslt_dscr="对账不平",
                            stmt_rslt="1"
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                };
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 3202对账明细 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("ybSettlementStmtService/stmtDetail")]
        [HttpPost]
        public async Task<IHttpActionResult> stmtDetail(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputStmtDetailRequest>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                string txtfile = fsiRequest.Input.data.file_qury_no;
                //验证文件路径是否存在
                if (!File.Exists(txtfile))
                {
                    throw new Exception($"根据传入的文件路径{txtfile}查询文件不存在！");
                }
                // 读取txt文件的内容，按照tab分割每一行
                string[] lines = File.ReadAllLines(txtfile);

                // 创建一个列表来存储分割后的行
                List<string[]> allLines = new List<string[]>();
                foreach (var line in lines)
                {
                    string[] columns = line.Split('\t');

                    // 确保每一行都有足够的列
                    if (columns.Length >= 3)
                    {
                        // 调整字段顺序，假设原来的顺序是：结算ID, 就诊ID, 人员编号, 医疗费总额, 基金支付总额, 个人账户支出, 退费结算标志
                        // 新的顺序应该是：人员编号, 就诊ID, 结算ID, 发送方报文ID, 对账结果, 退费结算标志, 备注
                        List<string> newColumns = new List<string>
                        {
                            columns[2], // 人员编号
                            columns[1], // 就诊ID
                            columns[0], // 结算ID
                            "1",        // 发送方报文ID
                            "0",        // 对账结果
                            columns[6], // 退费结算标志
                            "挡板接口数据，未关联核心库检索",       // 备注
                            columns[3], // 医疗费总额
                            columns[4], // 基金支付总额
                            columns[5]  // 个人账户支出
                        };
                        allLines.Add(newColumns.ToArray());
                    }
                }


                // 创建一个新的文件路径
                string newFilePath = Path.Combine(Path.GetDirectoryName(txtfile), "result.txt");

                // 将处理后的数据写入新的txt文件，按照tab分割每一列
                using (StreamWriter writer = new StreamWriter(newFilePath))
                {
                    foreach (var line in allLines)
                    {
                        writer.WriteLine(string.Join("\t", line));
                    }
                }

                // 创建压缩包的路径
                string zipFilePath = Path.Combine(Path.GetDirectoryName(txtfile), "FSI" + Path.GetFileNameWithoutExtension(txtfile) +"-"+dateTime.ToString("yyyyMMddHHmmssfff")+ ".zip");

                // 对新创建的txt文件进行压缩
                using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
                {
                    archive.CreateEntryFromFile(newFilePath, Path.GetFileName(newFilePath), CompressionLevel.Optimal);
                }
                ///删除写入的txt文件
                File.Delete(newFilePath);


                var FsiHeader = new FsiHeader<OutputStmtDetail>
                {
                    output = new OutputStmtDetail
                    {
                        fileinfo = new OutputFileUpload
                        {
                            filename = Path.GetFileName(zipFilePath),
                            file_qury_no = zipFilePath
                        },
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 5301人员慢特病查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fsiIntegratedQueryService/queryPsnOpspReg")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnOpspReg(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnOpspReg>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    if (string.IsNullOrEmpty(psn_no))
                    {
                        throw new Exception("参数校验失败：传入的人员编号psn_no为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_querypsnopspreg where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            List<FeedetailQueryPsnOpspReg> dataList = new List<FeedetailQueryPsnOpspReg>();
                            dt.Load(reader);
                            cmd.Parameters.Clear();
                            foreach (DataRow row in dt.Rows)
                            {
                                FeedetailQueryPsnOpspReg item = new FeedetailQueryPsnOpspReg
                                {
                                    opsp_dise_code = row["opsp_dise_code"].ToString(),
                                    opsp_dise_name = row["opsp_dise_name"].ToString(),
                                    exp_content = row["exp_content"].ToString(),
                                    begndate = row["begndate"].ToString(),
                                    enddate = row["enddate"].ToString(),
        
                                };
                                dataList.Add(item);
                            }
                            FsiHeader<OutputQueryPsnOpspReg> FsiHeader = new FsiHeader<OutputQueryPsnOpspReg>
                            {
                                output = new OutputQueryPsnOpspReg
                                {
                                    feedetail = dataList,
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 5206年度费用累计
        /// </summary>
        /// <returns></returns>
        [Route("fsiIntegratedQueryService/queryFixmedinsPracPsnSum")]
        [HttpPost]
        public async Task<IHttpActionResult> queryFixmedinsPracPsnSum(HttpRequestMessage request)
        {

            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryFixmedinsPracPsnSum>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    if (psn_no == "")
                    {
                        throw new Exception("传入的psn_no(人员编号)为空！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_queryfixmedinspracpsnsum where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            List<Cuminfo> dataList = new List<Cuminfo>();
                            foreach (DataRow row in dt.Rows)
                            {
                                Cuminfo item = new Cuminfo
                                {
                                    cum_type_code = row["cum_type_code"].ToString(),
                                    year = row["year"].ToString(),
                                    cum = (decimal)row["cum"],
                                    cum_ym = row["cum_ym"].ToString(),
                                    insutype = row["insutype"].ToString()
                                };
                                dataList.Add(item);
                            }
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var FsiHeader = new FsiHeader<outputCuminfo>
                            {
                                output = new outputCuminfo
                                {
                                    cuminfo = dataList
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 3101明细审核事前分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("riskConService/beforeAnalyze")]
        [HttpPost]
        public async Task<IHttpActionResult> beforeAnalyze(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string gend = fsiRequest.Input.data.patient_dtos.gend;//性别
                    string patn_id = fsiRequest.Input.data.patient_dtos.patn_id;//人员编号
                    string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id;//就诊id
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                    List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List;
                    if (fsiadmvs == "61")
                    {
                        fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.encounter_dtos.order_dtos;
                    }
                    else
                    {
                        fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        foreach (var item in fsi_order_dtos_List)
                        {
                            cmd.CommandText = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                            cmd.Parameters.AddWithValue("@med_list_codg", item.hilist_code);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                DataTable dt = new DataTable();
                                dt.Load(reader);
                                if (dt.Rows.Count >= 1)
                                {
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem = new List<Judge_result_detail_dtosItem>();
                                        Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                                        {
                                            vola_item_type = "1",
                                            mdtrt_id = curr_mdtrt_id,
                                            jrd_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            rx_id = item.rx_id,
                                            vola_amt = item.sumamt
                                        };
                                        JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}",
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = dt.Rows[i]["rule_name"].ToString(),
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }

                                }
                                dt.Dispose();
                                reader.Close();
                                reader.Dispose();
                            }

                            cmd.Parameters.Clear();
                        }
                    }
                    var FsiHeader = new FsiHeader<OutputriskConService>
                    {
                        output = new OutputriskConService
                        {
                            result = dataList
                        },
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3102明细审核事中分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("riskConService/courseAnalyze")]
        [HttpPost]
        public async Task<IHttpActionResult> courseAnalyze(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string gend = fsiRequest.Input.data.patient_dtos.gend;//性别
                    string patn_id = fsiRequest.Input.data.patient_dtos.patn_id;//人员编号
                    string curr_mdtrt_id = fsiRequest.Input.data.patient_dtos.curr_mdtrt_id;//就诊id
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                    List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List;
                    if (fsiadmvs=="61")
                    {
                        fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.encounter_dtos.order_dtos;
                    }
                    else
                    {
                        fsi_order_dtos_List = fsiRequest.Input.data.patient_dtos.fsi_encounter_dtos.fsi_order_dtos;
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        foreach (var item in fsi_order_dtos_List)
                        {
                            cmd.CommandText = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                            cmd.Parameters.AddWithValue("@med_list_codg", item.hilist_code);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                DataTable dt = new DataTable();
                                dt.Load(reader);
                                if (dt.Rows.Count >= 1)
                                {
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem = new List<Judge_result_detail_dtosItem>();
                                        Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                                        {
                                            vola_item_type = "1",
                                            mdtrt_id = curr_mdtrt_id,
                                            jrd_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            rx_id = item.rx_id,
                                            vola_amt = item.sumamt
                                        };
                                        JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                                        DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                        {
                                            judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                            rule_id = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}",
                                            vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                            rule_name = dt.Rows[i]["rule_name"].ToString(),
                                            mdtrt_id = curr_mdtrt_id,
                                            vola_amt_stas = "1",
                                            jr_id = Guid.NewGuid().ToString(),
                                            patn_id = patn_id,
                                            vola_amt = 1,
                                            sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                            vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                            vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                        };
                                        dataList.Add(riskConServiceresultInfo);
                                    }

                                }
                                dt.Dispose();
                                reader.Close();
                                reader.Dispose();
                            }

                            cmd.Parameters.Clear();
                        }
                    }
                    var FsiHeader = new FsiHeader<OutputriskConService>
                    {
                        output = new OutputriskConService
                        {
                            result = dataList
                        },
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3501 盘存上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsUpload")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsUpload(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsUpload>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO fsi_goodsupload  VALUES ( null,@fixmedins_code,@fixmedins_name, @med_list_codg,@fixmedins_hilist_id, @fixmedins_hilist_name, " +
                                "@rx_flag, @invdate, @inv_cnt, @manu_lotnum, @fixmedins_bchno, @manu_date, @expy_end, @memo, 0, @InputJson, @create_time,@update_time)";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.invinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.invinfo.fixmedins_hilist_id);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.invinfo.fixmedins_hilist_name);
                        cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.invinfo.rx_flag);
                        cmd.Parameters.AddWithValue("@invdate", fsiRequest.Input.invinfo.invdate);
                        cmd.Parameters.AddWithValue("@inv_cnt", fsiRequest.Input.invinfo.inv_cnt);
                        cmd.Parameters.AddWithValue("@manu_lotnum", fsiRequest.Input.invinfo.manu_lotnum);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.invinfo.fixmedins_bchno);
                        cmd.Parameters.AddWithValue("@manu_date", fsiRequest.Input.invinfo.manu_date);
                        cmd.Parameters.AddWithValue("@expy_end", fsiRequest.Input.invinfo.expy_end);
                        cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.invinfo.memo);
                        cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                        cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        await cmd.ExecuteNonQueryAsync();
                        cmd.Parameters.Clear();
                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 3502 库存变更
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsUpdate")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsUpdate(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsUpdate>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO fsi_goodsupdate  VALUES ( null,@fixmedins_code,@fixmedins_name, @med_list_codg,@inv_chg_type,@fixmedins_hilist_id, @fixmedins_hilist_name, " +
                                "@fixmedins_bchno, @pric, @cnt, @rx_flag, @inv_chg_time, @inv_chg_opter_name, @memo, @trdn_flag, 0, @InputJson, @create_time,@update_time)";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.invinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.invinfo.fixmedins_hilist_id);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.invinfo.fixmedins_hilist_name);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.invinfo.fixmedins_bchno);
                        cmd.Parameters.AddWithValue("@inv_chg_type", fsiRequest.Input.invinfo.inv_chg_type);
                        cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.invinfo.rx_flag);
                        cmd.Parameters.AddWithValue("@pric", fsiRequest.Input.invinfo.pric);
                        cmd.Parameters.AddWithValue("@cnt", fsiRequest.Input.invinfo.cnt);
                        cmd.Parameters.AddWithValue("@inv_chg_time", fsiRequest.Input.invinfo.inv_chg_time);
                        cmd.Parameters.AddWithValue("@inv_chg_opter_name", fsiRequest.Input.invinfo.inv_chg_opter_name);
                        cmd.Parameters.AddWithValue("@trdn_flag", fsiRequest.Input.invinfo.trdn_flag);
                        cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.invinfo.memo);
                        cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                        cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        await cmd.ExecuteNonQueryAsync();
                        cmd.Parameters.Clear();
                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3503 采购上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsBuy")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsBuy(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsBuy>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO fsi_goodsbuy  VALUES ( null,@fixmedins_code,@fixmedins_name,@med_list_codg,@fixmedins_hilist_id," +
                            " @fixmedins_hilist_name,@dynt_no,@fixmedins_bchno,@spler_name,@spler_pmtno," +
                            " @manu_lotnum,@prodentp_name, @aprvno, @manu_date,@expy_end," +
                            "@finl_trns_pric,@purc_retn_cnt,@purc_invo_codg,@purc_invo_no, @rx_flag," +
                        " @purc_retn_stoin_time, @purc_retn_opter_name, @prod_geay_flag,@memo,0,0," +
                        " @InputJson, @create_time,@update_time)";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.purcinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.purcinfo.fixmedins_hilist_id);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.purcinfo.fixmedins_hilist_name);
                        
                        cmd.Parameters.AddWithValue("@dynt_no", fsiRequest.Input.purcinfo.dynt_no);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.purcinfo.fixmedins_bchno);
                        cmd.Parameters.AddWithValue("@spler_name", fsiRequest.Input.purcinfo.spler_name);
                        cmd.Parameters.AddWithValue("@spler_pmtno", fsiRequest.Input.purcinfo.spler_pmtno);
                        cmd.Parameters.AddWithValue("@manu_lotnum", fsiRequest.Input.purcinfo.manu_lotnum);
                        
                        cmd.Parameters.AddWithValue("@prodentp_name", fsiRequest.Input.purcinfo.prodentp_name);
                        cmd.Parameters.AddWithValue("@aprvno", fsiRequest.Input.purcinfo.aprvno);
                        cmd.Parameters.AddWithValue("@manu_date", fsiRequest.Input.purcinfo.manu_date);
                        cmd.Parameters.AddWithValue("@expy_end", fsiRequest.Input.purcinfo.expy_end);
                        cmd.Parameters.AddWithValue("@finl_trns_pric", fsiRequest.Input.purcinfo.finl_trns_pric);
                        
                        cmd.Parameters.AddWithValue("@purc_retn_cnt", fsiRequest.Input.purcinfo.purc_retn_cnt);
                        cmd.Parameters.AddWithValue("@purc_invo_codg", fsiRequest.Input.purcinfo.purc_invo_codg);
                        cmd.Parameters.AddWithValue("@purc_invo_no", fsiRequest.Input.purcinfo.purc_invo_no);
                        cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.purcinfo.rx_flag);
                        cmd.Parameters.AddWithValue("@purc_retn_stoin_time", fsiRequest.Input.purcinfo.purc_retn_stoin_time);
                        
                        cmd.Parameters.AddWithValue("@purc_retn_opter_name", fsiRequest.Input.purcinfo.purc_retn_opter_name);
                        cmd.Parameters.AddWithValue("@prod_geay_flag", fsiRequest.Input.purcinfo.prod_geay_flag);
                        cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.purcinfo.memo);
                        cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                        cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        await cmd.ExecuteNonQueryAsync();
                        cmd.Parameters.Clear();
                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 3504 采购退货上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsBuyReturn")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsBuyReturn(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsBuy>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_goodsbuy  where fixmedins_code =@fixmedins_code and med_list_codg =@med_list_codg and fixmedins_hilist_id =@fixmedins_hilist_id and fixmedins_bchno=@fixmedins_bchno and state =0 and datatype=0";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.purcinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.purcinfo.fixmedins_hilist_id);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.purcinfo.fixmedins_bchno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            cmd.Parameters.Clear();
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if(dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询采购上传记录表失败！根据传入的机构代码：{fsiRequest.fixmedins_code} 医保目录编码：{fsiRequest.Input.purcinfo.med_list_codg} 医疗机构内部编码：{fsiRequest.Input.purcinfo.fixmedins_hilist_id} 批次号：{fsiRequest.Input.purcinfo.fixmedins_bchno}查询到的采购上传记录总数为：{dt.Rows.Count}");
                            }
                            else
                            {
                                cmd.CommandText = "INSERT INTO fsi_goodsbuy  VALUES ( null,@fixmedins_code,@fixmedins_name,@med_list_codg,@fixmedins_hilist_id," +
                                " @fixmedins_hilist_name,@dynt_no,@fixmedins_bchno,@spler_name,@spler_pmtno," +
                                " @manu_lotnum,@prodentp_name, @aprvno, @manu_date,@expy_end," +
                                "@finl_trns_pric,@purc_retn_cnt,@purc_invo_codg,@purc_invo_no, @rx_flag," +
                                " @purc_retn_stoin_time, @purc_retn_opter_name, @prod_geay_flag,@memo, 1,0," +
                                " @InputJson, @create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.purcinfo.med_list_codg);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.purcinfo.fixmedins_hilist_id);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.purcinfo.fixmedins_hilist_name);

                                cmd.Parameters.AddWithValue("@dynt_no", fsiRequest.Input.purcinfo.dynt_no);
                                cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.purcinfo.fixmedins_bchno);
                                cmd.Parameters.AddWithValue("@spler_name", fsiRequest.Input.purcinfo.spler_name);
                                cmd.Parameters.AddWithValue("@spler_pmtno", fsiRequest.Input.purcinfo.spler_pmtno);
                                cmd.Parameters.AddWithValue("@manu_lotnum", fsiRequest.Input.purcinfo.manu_lotnum);

                                cmd.Parameters.AddWithValue("@prodentp_name", fsiRequest.Input.purcinfo.prodentp_name);
                                cmd.Parameters.AddWithValue("@aprvno", fsiRequest.Input.purcinfo.aprvno);
                                cmd.Parameters.AddWithValue("@manu_date", fsiRequest.Input.purcinfo.manu_date);
                                cmd.Parameters.AddWithValue("@expy_end", fsiRequest.Input.purcinfo.expy_end);
                                cmd.Parameters.AddWithValue("@finl_trns_pric", fsiRequest.Input.purcinfo.finl_trns_pric);

                                cmd.Parameters.AddWithValue("@purc_retn_cnt", fsiRequest.Input.purcinfo.purc_retn_cnt);
                                cmd.Parameters.AddWithValue("@purc_invo_codg", fsiRequest.Input.purcinfo.purc_invo_codg);
                                cmd.Parameters.AddWithValue("@purc_invo_no", fsiRequest.Input.purcinfo.purc_invo_no);
                                cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.purcinfo.rx_flag);
                                cmd.Parameters.AddWithValue("@purc_retn_stoin_time", fsiRequest.Input.purcinfo.purc_retn_stoin_time);

                                cmd.Parameters.AddWithValue("@purc_retn_opter_name", fsiRequest.Input.purcinfo.purc_retn_opter_name);
                                cmd.Parameters.AddWithValue("@prod_geay_flag", fsiRequest.Input.purcinfo.prod_geay_flag);
                                cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.purcinfo.memo);
                                cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                        }
                        
                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3505 销售上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsSell")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsSell(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsSell>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO fsi_goodsSell VALUES ( " +
                            " null,@fixmedins_code,@fixmedins_name,@med_list_codg,@fixmedins_hilist_id," +
                            " @fixmedins_hilist_name,@fixmedins_bchno,@prsc_dr_cert_type,@prsc_dr_certno,@prsc_dr_name," +
                            " @phar_cert_type,@phar_certno, @phar_name, @phar_prac_cert_no,@hi_feesetl_type," +
                            " @setl_id,@mdtrt_sn,@psn_no,@psn_cert_type, @certno," +
                            " @psn_name, @manu_lotnum, @manu_date,@expy_end,@rx_flag," +
                            " @trdn_flag, @finl_trns_pric, @rxno,@rx_circ_flag,@rtal_docno," +
                            " @stoout_no, @bchno, @drug_trac_codg,@drug_prod_barc,@shelf_posi," +
                            " @sel_retn_cnt, @sel_retn_time, @sel_retn_opter_name,@memo,@mdtrt_setl_type," +
                            " 0,0,@InputJson, @create_time,@update_time)";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.selinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.selinfo.fixmedins_hilist_id);
                        
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.selinfo.fixmedins_hilist_name);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.selinfo.fixmedins_bchno);
                        cmd.Parameters.AddWithValue("@prsc_dr_cert_type", fsiRequest.Input.selinfo.prsc_dr_cert_type);
                        cmd.Parameters.AddWithValue("@prsc_dr_certno", fsiRequest.Input.selinfo.prsc_dr_certno);
                        cmd.Parameters.AddWithValue("@prsc_dr_name", fsiRequest.Input.selinfo.prsc_dr_name);

                        cmd.Parameters.AddWithValue("@phar_cert_type", fsiRequest.Input.selinfo.phar_cert_type);
                        cmd.Parameters.AddWithValue("@phar_certno", fsiRequest.Input.selinfo.phar_certno);
                        cmd.Parameters.AddWithValue("@phar_name", fsiRequest.Input.selinfo.phar_name);
                        cmd.Parameters.AddWithValue("@phar_prac_cert_no", fsiRequest.Input.selinfo.phar_prac_cert_no);
                        cmd.Parameters.AddWithValue("@hi_feesetl_type", fsiRequest.Input.selinfo.hi_feesetl_type);

                        cmd.Parameters.AddWithValue("@setl_id", fsiRequest.Input.selinfo.setl_id);
                        cmd.Parameters.AddWithValue("@mdtrt_sn", fsiRequest.Input.selinfo.mdtrt_sn);
                        cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.selinfo.psn_no);
                        cmd.Parameters.AddWithValue("@psn_cert_type", fsiRequest.Input.selinfo.psn_cert_type);
                        cmd.Parameters.AddWithValue("@certno", fsiRequest.Input.selinfo.certno);

                        cmd.Parameters.AddWithValue("@psn_name", fsiRequest.Input.selinfo.psn_name);
                        cmd.Parameters.AddWithValue("@manu_lotnum", fsiRequest.Input.selinfo.manu_lotnum);
                        cmd.Parameters.AddWithValue("@manu_date", fsiRequest.Input.selinfo.manu_date);
                        cmd.Parameters.AddWithValue("@expy_end", fsiRequest.Input.selinfo.expy_end);
                        cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.selinfo.rx_flag);

                        cmd.Parameters.AddWithValue("@trdn_flag", fsiRequest.Input.selinfo.trdn_flag);
                        cmd.Parameters.AddWithValue("@finl_trns_pric", fsiRequest.Input.selinfo.finl_trns_pric);
                        cmd.Parameters.AddWithValue("@rxno", fsiRequest.Input.selinfo.rxno);
                        cmd.Parameters.AddWithValue("@rx_circ_flag", fsiRequest.Input.selinfo.rx_circ_flag);
                        cmd.Parameters.AddWithValue("@rtal_docno", fsiRequest.Input.selinfo.rtal_docno);

                        cmd.Parameters.AddWithValue("@stoout_no", fsiRequest.Input.selinfo.stoout_no);
                        cmd.Parameters.AddWithValue("@bchno", fsiRequest.Input.selinfo.bchno);
                        cmd.Parameters.AddWithValue("@drug_trac_codg", fsiRequest.Input.selinfo.drug_trac_codg);
                        cmd.Parameters.AddWithValue("@drug_prod_barc", fsiRequest.Input.selinfo.drug_prod_barc);
                        cmd.Parameters.AddWithValue("@shelf_posi", fsiRequest.Input.selinfo.shelf_posi);

                        cmd.Parameters.AddWithValue("@sel_retn_cnt", fsiRequest.Input.selinfo.sel_retn_cnt);
                        cmd.Parameters.AddWithValue("@sel_retn_time", fsiRequest.Input.selinfo.sel_retn_time);
                        cmd.Parameters.AddWithValue("@sel_retn_opter_name", fsiRequest.Input.selinfo.sel_retn_opter_name);
                        cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.selinfo.memo);
                        cmd.Parameters.AddWithValue("@mdtrt_setl_type", fsiRequest.Input.selinfo.mdtrt_setl_type);


                        cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                        cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                        await cmd.ExecuteNonQueryAsync();
                        cmd.Parameters.Clear();
                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 3506 销售退货
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsSellReturn")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsSellReturn(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsSell>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_goodsSell  where fixmedins_code =@fixmedins_code and med_list_codg =@med_list_codg and fixmedins_hilist_id =@fixmedins_hilist_id and fixmedins_bchno=@fixmedins_bchno and state =0 and datatype=0";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.selinfo.med_list_codg);
                        cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.selinfo.fixmedins_hilist_id);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.selinfo.fixmedins_bchno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            cmd.Parameters.Clear();
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询销售上传记录表失败！根据传入的机构代码：{fsiRequest.fixmedins_code} 医保目录编码：{fsiRequest.Input.selinfo.med_list_codg} 医疗机构内部编码：{fsiRequest.Input.selinfo.fixmedins_hilist_id} 批次号：{fsiRequest.Input.selinfo.fixmedins_bchno}查询到的销售上传记录总数为：{dt.Rows.Count}");
                            }
                            else
                            {
                                cmd.CommandText = "INSERT INTO fsi_goodsSell VALUES ( " +
                                " null,@fixmedins_code,@fixmedins_name,@med_list_codg,@fixmedins_hilist_id," +
                                " @fixmedins_hilist_name,@fixmedins_bchno,@prsc_dr_cert_type,@prsc_dr_certno,@prsc_dr_name," +
                                " @phar_cert_type,@phar_certno, @phar_name, @phar_prac_cert_no,@hi_feesetl_type," +
                                " @setl_id,@mdtrt_sn,@psn_no,@psn_cert_type, @certno," +
                                " @psn_name, @manu_lotnum, @manu_date,@expy_end,@rx_flag," +
                                " @trdn_flag, @finl_trns_pric, @rxno,@rx_circ_flag,@rtal_docno," +
                                " @stoout_no, @bchno, @drug_trac_codg,@drug_prod_barc,@shelf_posi," +
                                " @sel_retn_cnt, @sel_retn_time, @sel_retn_opter_name,@memo,@mdtrt_setl_type," +
                                " 1,0,@InputJson, @create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@med_list_codg", fsiRequest.Input.selinfo.med_list_codg);
                                cmd.Parameters.AddWithValue("@fixmedins_hilist_id", fsiRequest.Input.selinfo.fixmedins_hilist_id);

                                cmd.Parameters.AddWithValue("@fixmedins_hilist_name", fsiRequest.Input.selinfo.fixmedins_hilist_name);
                                cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.selinfo.fixmedins_bchno);
                                cmd.Parameters.AddWithValue("@prsc_dr_cert_type", fsiRequest.Input.selinfo.prsc_dr_cert_type);
                                cmd.Parameters.AddWithValue("@prsc_dr_certno", fsiRequest.Input.selinfo.prsc_dr_certno);
                                cmd.Parameters.AddWithValue("@prsc_dr_name", fsiRequest.Input.selinfo.prsc_dr_name);

                                cmd.Parameters.AddWithValue("@phar_cert_type", fsiRequest.Input.selinfo.phar_cert_type);
                                cmd.Parameters.AddWithValue("@phar_certno", fsiRequest.Input.selinfo.phar_certno);
                                cmd.Parameters.AddWithValue("@phar_name", fsiRequest.Input.selinfo.phar_name);
                                cmd.Parameters.AddWithValue("@phar_prac_cert_no", fsiRequest.Input.selinfo.phar_prac_cert_no);
                                cmd.Parameters.AddWithValue("@hi_feesetl_type", fsiRequest.Input.selinfo.hi_feesetl_type);

                                cmd.Parameters.AddWithValue("@setl_id", fsiRequest.Input.selinfo.setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_sn", fsiRequest.Input.selinfo.mdtrt_sn);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.selinfo.psn_no);
                                cmd.Parameters.AddWithValue("@psn_cert_type", fsiRequest.Input.selinfo.psn_cert_type);
                                cmd.Parameters.AddWithValue("@certno", fsiRequest.Input.selinfo.certno);

                                cmd.Parameters.AddWithValue("@psn_name", fsiRequest.Input.selinfo.psn_name);
                                cmd.Parameters.AddWithValue("@manu_lotnum", fsiRequest.Input.selinfo.manu_lotnum);
                                cmd.Parameters.AddWithValue("@manu_date", fsiRequest.Input.selinfo.manu_date);
                                cmd.Parameters.AddWithValue("@expy_end", fsiRequest.Input.selinfo.expy_end);
                                cmd.Parameters.AddWithValue("@rx_flag", fsiRequest.Input.selinfo.rx_flag);

                                cmd.Parameters.AddWithValue("@trdn_flag", fsiRequest.Input.selinfo.trdn_flag);
                                cmd.Parameters.AddWithValue("@finl_trns_pric", fsiRequest.Input.selinfo.finl_trns_pric);
                                cmd.Parameters.AddWithValue("@rxno", fsiRequest.Input.selinfo.rxno);
                                cmd.Parameters.AddWithValue("@rx_circ_flag", fsiRequest.Input.selinfo.rx_circ_flag);
                                cmd.Parameters.AddWithValue("@rtal_docno", fsiRequest.Input.selinfo.rtal_docno);

                                cmd.Parameters.AddWithValue("@stoout_no", fsiRequest.Input.selinfo.stoout_no);
                                cmd.Parameters.AddWithValue("@bchno", fsiRequest.Input.selinfo.bchno);
                                cmd.Parameters.AddWithValue("@drug_trac_codg", fsiRequest.Input.selinfo.drug_trac_codg);
                                cmd.Parameters.AddWithValue("@drug_prod_barc", fsiRequest.Input.selinfo.drug_prod_barc);
                                cmd.Parameters.AddWithValue("@shelf_posi", fsiRequest.Input.selinfo.shelf_posi);

                                cmd.Parameters.AddWithValue("@sel_retn_cnt", fsiRequest.Input.selinfo.sel_retn_cnt);
                                cmd.Parameters.AddWithValue("@sel_retn_time", fsiRequest.Input.selinfo.sel_retn_time);
                                cmd.Parameters.AddWithValue("@sel_retn_opter_name", fsiRequest.Input.selinfo.sel_retn_opter_name);
                                cmd.Parameters.AddWithValue("@memo", fsiRequest.Input.selinfo.memo);
                                cmd.Parameters.AddWithValue("@mdtrt_setl_type", fsiRequest.Input.selinfo.mdtrt_setl_type);


                                cmd.Parameters.AddWithValue("@InputJson", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                        }

                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 3507 上传记录删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsInfoDelete")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsInfoDelete(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsInfoDelete>>(request.Content.ReadAsStringAsync().Result);
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                    string fixmedins_code = fsiRequest.fixmedins_code;
                    string fixmedins_bchno = fsiRequest.Input.data.fixmedins_bchno;
                    string inv_data_type = fsiRequest.Input.data.inv_data_type;

                    string tablename=string.Empty;
                    switch (inv_data_type)
                    {
                        case "1":
                            tablename = "fsi_goodsupload";
                            break;
                        case "2":
                            tablename = "fsi_goodsupdate";
                            break;
                        case "3":
                            tablename = "fsi_goodsbuy";
                            break;
                        case "4":
                            tablename = "fsi_goodssell";
                            break;
                        default:
                            throw new Exception($"校验进销存数据类型失败：进销存数据类型{inv_data_type}未被定义！");
                    }

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = $"select * from {tablename}  where fixmedins_code =@fixmedins_code and fixmedins_bchno=@fixmedins_bchno and state =0";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                        cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.data.fixmedins_bchno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            cmd.Parameters.Clear();
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                throw new Exception($"查询{tablename}记录表失败！根据传入的机构代码：{fixmedins_code} 上传类型：{inv_data_type}  批次号：{fixmedins_bchno} 查询到的记录总数为：{dt.Rows.Count}");
                            }
                            else
                            {
                                cmd.CommandText = $"update  {tablename} set state=1,update_time= @update_time where fixmedins_code =@fixmedins_code and fixmedins_bchno=@fixmedins_bchno and state =0 ";
                                cmd.Parameters.AddWithValue("@tablename", tablename);
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_bchno", fsiRequest.Input.data.fixmedins_bchno);
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                        }

                    }
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);

                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 9101文件上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fileupload/upload")]
        [HttpPost]
        public async Task<IHttpActionResult> upload(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputFileupload>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                string zipPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\file", $"{fsiRequest.fixmedins_code}-{dateTime.ToString("yyyyMMddHHmmssfff")}.zip");
                byte[] byteArray = Array.ConvertAll(fsiRequest.Input.fsUploadIn.@in, i => (byte)i);
                File.WriteAllBytes(zipPath, byteArray);
                // 将zip解压到指定目录，并自动覆盖重复文件
                string unzipPath = AppDomain.CurrentDomain.BaseDirectory + "\\file";
                using (var archive = new ZipArchive(new MemoryStream(byteArray), ZipArchiveMode.Read))
                {
                    foreach (var entry in archive.Entries)
                    {
                        string destPath = Path.Combine(unzipPath, entry.FullName);
                        Directory.CreateDirectory(Path.GetDirectoryName(destPath)); // 确保目标路径的目录存在
                        entry.ExtractToFile(destPath, true); // true 表示覆盖现有文件
                    }
                }
                //解压后删除zip文件
                File.Delete(zipPath);

                var FsiHeader = new FsiHeader<OutputFileUpload>
                {
                    output = new OutputFileUpload
                    {
                        filename= fsiRequest.Input.fsUploadIn.filename,
                        file_qury_no = unzipPath+"\\"+fsiRequest.Input.fsUploadIn.filename,
                        dld_endtime=dateTime.AddDays(1).ToString("yyyyMMddHHmmssfff"),
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 9102文件下载
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fileupload/download")]
        [HttpPost]
        public async Task<IHttpActionResult> download(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputFileDownload>>(request.Content.ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }
                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                string filePath = fsiRequest.Input.fsDownloadIn.file_qury_no;
                //判断传入的文件是否存在
                if (!File.Exists(filePath))
                {
                    throw new Exception("根据传入的文件路径查询不到文件！");
                }
                var fileBytes = System.IO.File.ReadAllBytes(filePath);
                var fileName = Path.GetFileName(filePath);
                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(fileBytes)
                };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                //删除文件
                File.Delete(filePath);
                return ResponseMessage(result);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                return Json(FsiHeader);
            }
        }




        ///以下接口并非浙江省接口，因为路由冲突 需要定义在FSI/API路径下

        /// <summary>
        /// 2101
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPre")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsPre(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    Console.WriteLine(request.Content.ReadAsStringAsync().Result);
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }
                            string mdtrt_id = rnd.Next(10000000, 90000000).ToString();
                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                if (fsiRequest.Input.druginfo.med_type != "41"&& fsiadmvs=="33")
                                {
                                    cmd.CommandText = "SELECT * FROM fsi_prescription_detail a  left JOIN fsi_prescription b  on a.auth_rxno = b.auth_rxno where b.hi_rxno =@hi_rxno  and a.med_list_codg=@med_list_codg ";
                                    cmd.Parameters.AddWithValue("@hi_rxno", item.rxno);
                                    cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                    {
                                        DataTable dt = new DataTable();
                                        dt.Load(reader);
                                        if (dt.Rows.Count < 1)
                                        {
                                            throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。");
                                        }
                                    }
                                    cmd.Parameters.Clear();
                                }
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族

                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付

                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,

                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出

                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付

                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 0);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", "");
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", "");
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"预结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 2102
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccounts")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccounts(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }

                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            //序列化拓展字段
                            Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                            {
                                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2),
                                Q0001 = 0,
                                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2)
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                            string mdtrt_id;
                            string setl_id;
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            //Setldetail detail1 = new Setldetail
                            //{
                            //    fund_pay_type = "650102",
                            //    fund_payamt = 11,
                            //    setl_proc_info = null,
                            //    crt_payb_lmt_amt = 0,
                            //    inscp_scp_amt = 0,
                            //    fund_pay_type_name = "罕见病用药"
                            //};
                            //setldetail.Add(detail1);
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        exp_content = expcontentJson,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,
                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        setl_id = setl_id,
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", fsiRequest.Input.druginfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        
        /// <summary>
        /// 2102 V2 河北医保
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsV2")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsV2(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }

                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            //序列化拓展字段
                            Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                            {
                                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2),
                                Q0001 = 0,
                                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2)
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                            string mdtrt_id;
                            string setl_id;
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            //Setldetail detail1 = new Setldetail
                            //{
                            //    fund_pay_type = "650102",
                            //    fund_payamt = 11,
                            //    setl_proc_info = null,
                            //    crt_payb_lmt_amt = 0,
                            //    inscp_scp_amt = 0,
                            //    fund_pay_type_name = "罕见病用药"
                            //};
                            //setldetail.Add(detail1);
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        exp_content = expcontentJson,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,
                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        setl_id = setl_id,
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", fsiRequest.Input.druginfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        
        /// <summary>
        /// 河北医保 电子凭证入参地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("hsecfc/localQrCodeQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> localQrCodeQuery(HttpRequestMessage request)
        {
            string orgid = "";
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEcCodeHeader<DataEcCodeRequest>>(request.Content.ReadAsStringAsync().Result);
                    orgid = fsiRequest.orgId;
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dt = new DataTable();
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", FsiDatainfo.Ecccodecardno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                var FsiHeader = new FsiEcCodeHeader<DataFsiEcCode>
                                {
                                    code = 0,
                                    message = "成功",
                                    orgId = orgid,
                                    data = new DataFsiEcCode
                                    {
                                        chnlId = PublicMethod.GenerateRandomString(32),
                                        ecIndexNo = PublicMethod.GenerateRandomString(32),
                                        ecQrCode = PublicMethod.GenerateRandomString(28),
                                        ecToken = PublicMethod.GenerateRandomString(38),
                                        idNo = FsiDatainfo.Ecccodecardno,
                                        idType = "01",
                                        insuOrg = "",
                                        userName = dt.Rows[0]["psn_name"].ToString(),
                                    }
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询人员信息表失败！根据传入的人员证件号码【{FsiDatainfo.Ecccodecardno}】查询到的人员信息总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiEcCodeHeader<DataFsiEcCode>
                    {
                        code = -1,
                        message = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                        orgId = orgid

                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        //以下接口为门诊/医院接口，开发中暂时只支持浙江省

        /// <summary>
        /// 2201门诊挂号
        /// </summary>
        /// <returns></returns>
        [Route("outpatientDocInfoService/outpatientRregistration")]
        [HttpPost]
        public async Task<IHttpActionResult> outpatientRregistration(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientRregistration>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string ipt_otp_no = fsiRequest.Input.data.ipt_otp_no;

                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || string.IsNullOrEmpty(ipt_otp_no))
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|住院/门诊号为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            //设置就诊id
                            string mdtrt_id;
  
                            //浙江省 如果是异地 则结算id需要短一点，不然会报错 模拟异地的结算id长度 取人员参保地长度前四位是否和入参参保地前四位是否一致
                            if (fsiRequest.insuplc_admdvs.Substring(0, 4) != fsiRequest.mdtrtarea_admvs.Substring(0, 4))
                            {
                                mdtrt_id = $"{dtunix}";
                            }
                            else
                            {
                                mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            }
      

                            //组装返回参数
                            var FsiHeader = new FsiHeader<OutputOutpatientRregistration>
                            {
                                output = new OutputOutpatientRregistration
                                {

                                    data=new OutpatientRregistration
                                    {
                                        mdtrt_id=mdtrt_id,
                                        psn_no=psn_no,
                                        ipt_otp_no=ipt_otp_no
                                    }

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };

                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {

                                // 插入挂号记录
                                cmd.CommandText = "INSERT INTO `data`.`fsi_hospital_register` ( `fixmedins_code`, `fixmedins_name`, `register_state`, `psn_no`, `insutype`, " +
                                                  "`begntime`, `ipt_otp_no`, `mdtrt_id`, `atddr_no`, `dr_name`, `dept_code`, `dept_name`, `caty`, `exp_content`, " +
                                                  "`outpatientRregistrationInput`, `outpatientRregistrationOutput`, `outpatientRegistrationCancelInput`, " +
                                                  "`outpatientRegistrationCancelOutput`, `create_time`, `update_time`) " +
                                                  "VALUES ( @fixmedins_code, @fixmedins_name, @register_state, @psn_no, @insutype, @begntime, @ipt_otp_no, " +
                                                  "@mdtrt_id, @atddr_no, @dr_name, @dept_code, @dept_name, @caty, @exp_content, " +
                                                  "@outpatientRregistrationInput, @outpatientRregistrationOutput, @outpatientRegistrationCancelInput, " +
                                                  "@outpatientRegistrationCancelOutput, @create_time, @update_time);";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@register_state", 0);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@insutype", fsiRequest.Input.data.insutype);  
                                cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.data.begntime);  
                                cmd.Parameters.AddWithValue("@ipt_otp_no", fsiRequest.Input.data.ipt_otp_no); 
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@atddr_no", fsiRequest.Input.data.atddr_no); 
                                cmd.Parameters.AddWithValue("@dr_name", fsiRequest.Input.data.dr_name); 
                                cmd.Parameters.AddWithValue("@dept_code", fsiRequest.Input.data.dept_code);  
                                cmd.Parameters.AddWithValue("@dept_name", fsiRequest.Input.data.dept_name);  
                                cmd.Parameters.AddWithValue("@caty",fsiRequest.Input.data.caty);  
                                cmd.Parameters.AddWithValue("@exp_content", fsiRequest.Input.data.exp_content); 
                                cmd.Parameters.AddWithValue("@outpatientRregistrationInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@outpatientRregistrationOutput", JsonString);
                                cmd.Parameters.AddWithValue("@outpatientRegistrationCancelInput", "");
                                cmd.Parameters.AddWithValue("@outpatientRegistrationCancelOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));

                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();

                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"门诊挂号处理失败：插入挂号记录表失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            //Console.WriteLine("ok 参数组织完成进入等待！\r\n"+FsiHeader);
                            //Thread.Sleep(60000);
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 2202门诊挂号撤销
        /// </summary>
        /// <returns></returns>
        [Route("outpatientDocInfoService/outpatientRegistrationCancel")]
        [HttpPost]
        public async Task<IHttpActionResult> outpatientRegistrationCancel(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientRegistrationCancel>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string fixmedins_code = fsiRequest.fixmedins_code;
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string mdtrtid = fsiRequest.Input.data.mdtrt_id;
                    string ipt_otp_no = fsiRequest.Input.data.ipt_otp_no;
                    if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(mdtrtid)||string.IsNullOrEmpty(ipt_otp_no))
                    {
                        throw new Exception("参数校验失败：传入的住院/门诊号|人员编号||就诊ID为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    DataTable dt = new DataTable();
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            cmd.CommandText = "select * from fsi_hospital_register where psn_no=@psn_no and mdtrt_id=@mdtrt_id and ipt_otp_no=@ipt_otp_no and register_state=0";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                            cmd.Parameters.AddWithValue("@ipt_otp_no", ipt_otp_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dt.Load(reader);
                                if (dt.Rows.Count != 1)
                                {
                                    throw new Exception($"查询挂号记录信息表失败！查询到的挂号记录总数为：{dt.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            var FsiHeader = new FsiHeader<outputsignInOut>
                            {
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "update fsi_hospital_register  set register_state= @register_state,outpatientRegistrationCancelInput=@outpatientRegistrationCancelInput,outpatientRegistrationCancelOutput=@outpatientRegistrationCancelOutput,update_time=@update_time where psn_no=@psn_no and mdtrt_id=@mdtrt_id and ipt_otp_no=@ipt_otp_no and register_state=0";
                                cmd.Parameters.AddWithValue("@register_state", 2);
                                cmd.Parameters.AddWithValue("@outpatientRegistrationCancelInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@outpatientRegistrationCancelOutput", JsonString);
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                                cmd.Parameters.AddWithValue("@ipt_otp_no", ipt_otp_no);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"门诊挂号数据处理失败：更新门诊挂号记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

		/// <summary>
		/// 2203门诊就诊信息上传
		/// </summary>
		/// <returns></returns>
		[Route("outpatientDocInfoService/outpatientMdtrtinfoUpA")]
		[HttpPost]
		public async Task<IHttpActionResult> outpatientMdtrtinfoUpA(HttpRequestMessage request)
		{
			string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
			using (MySqlConnection conn = new MySqlConnection(connectionString))
			{
				try
				{
					if (FsiDatainfo.stateFsiApi == false)
					{
						throw new Exception("该接口已被控制台停用！请联系管理员！");
					}
					var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientMdtrtinfoUpA>>(request.Content.ReadAsStringAsync().Result);
					string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string mdtrt_id = fsiRequest.Input.mdtrtinfo.mdtrt_id;
                    string psn_no = fsiRequest.Input.mdtrtinfo.psn_no;

					if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || string.IsNullOrEmpty(mdtrt_id))
					{
						throw new Exception("参数校验失败：传入的机构代码|人员编号|就诊ID为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
					}
					if (FsiDatainfo.statesignon == true)
					{
						if (string.IsNullOrEmpty(fsiRequest.sign_no))
						{
							throw new Exception("校验签到信息失败：传入的签到号为空！");
						}
						bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

						if (sign == false)
						{
							throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
						}
					}
					Random rnd = new Random();
					DateTime dateTime = DateTime.Now;
					DataTable dtpsninfo = new DataTable();
					long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
					string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
					await conn.OpenAsync();
					using (MySqlTransaction transaction = conn.BeginTransaction())
					{
						using (MySqlCommand cmd = conn.CreateCommand())
						{
							cmd.CommandText = "select * from fsi_hospital_register where psn_no=@psn_no and register_state=0 and mdtrt_id=@mdtrt_id";
							cmd.Parameters.AddWithValue("@psn_no", psn_no);
							cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
							using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
							{
								dtpsninfo.Load(reader);
								if (dtpsninfo.Rows.Count != 1)
								{
									throw new Exception($"查询挂号记录表失败！查询到的未撤销的挂号记录总数为：{dtpsninfo.Rows.Count}");
								}
								cmd.Parameters.Clear();
							}


							//组装返回参数
							var FsiHeader = new FsiHeader<outputsignInOut>
							{
								infcode = 0,
								warn_msg = null,
								cainfo = null,
								err_msg = "success",
								refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
								signtype = null,
								respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
								inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
							};

							string JsonString = JsonConvert.SerializeObject(FsiHeader);
							cmd.Transaction = transaction;
							try
							{
                                cmd.CommandText = "INSERT INTO `data`.`fsi_hospital_uploadmedicalrecords` (`fixmedins_code`, `fixmedins_name`, `mdtrt_id`, `psn_no`, `med_type`, `begntime`, `main_cond_dscr`, `dise_codg`, `dise_name`, `diseinfo`, `outpatientMdtrtinfoUpInput`, `outpatientMdtrtinfoUpOutput`, `create_time`, `update_time`) " +
				                "VALUES (@fixmedins_code, @fixmedins_name, @mdtrt_id, @psn_no, @med_type, @begntime, @main_cond_dscr, @dise_codg, @dise_name, @diseinfo, @outpatientMdtrtinfoUpInput, @outpatientMdtrtinfoUpOutput, @create_time, @update_time);";
								cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
								cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
								cmd.Parameters.AddWithValue("@mdtrt_id", fsiRequest.Input.mdtrtinfo.mdtrt_id);
								cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.mdtrtinfo.psn_no);
								cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.mdtrtinfo.med_type);
								cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.mdtrtinfo.begntime);
								cmd.Parameters.AddWithValue("@main_cond_dscr", fsiRequest.Input.mdtrtinfo.main_cond_dscr);
								cmd.Parameters.AddWithValue("@dise_codg", fsiRequest.Input.mdtrtinfo.dise_codg);
								cmd.Parameters.AddWithValue("@dise_name", fsiRequest.Input.mdtrtinfo.dise_name);
								cmd.Parameters.AddWithValue("@diseinfo", JsonConvert.SerializeObject(fsiRequest.Input.diseinfo));
								cmd.Parameters.AddWithValue("@outpatientMdtrtinfoUpInput", request.Content.ReadAsStringAsync().Result);
								cmd.Parameters.AddWithValue("@outpatientMdtrtinfoUpOutput", JsonString);
								cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
								cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));

								await cmd.ExecuteNonQueryAsync();
								cmd.Parameters.Clear();

							}
							catch (Exception ex)
							{
								transaction.Rollback();
								throw new Exception($"门诊就诊信息上传失败：插入门诊就诊信息记录表失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
							}
							transaction.Commit();
							//Console.WriteLine("ok 参数组织完成进入等待！\r\n"+FsiHeader);
							//Thread.Sleep(60000);
							return Json(FsiHeader);
						}
					}
				}
				catch (Exception ex)
				{
					string Errnum = LogHelper.GetErrornumber();
					var FsiHeader = new FsiHeader<outputsignInOut>
					{
						infcode = -1,
						err_msg = $"[{Errnum}]调用自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
					};
					return Json(FsiHeader);
				}
				finally
				{
					if (conn.State == ConnectionState.Open)
					{
						await conn.CloseAsync();
					}
				}
			}
		}
	}
}
